package com.yb.guigu.pick.mqbackup.listener;

import com.rabbitmq.client.Channel;
import com.yb.guigu.pick.core.constant.RabbitMQConstant;
import com.yb.guigu.pick.core.domain.mq.BackupMQSend;
import com.yb.guigu.pick.mqbackup.entity.MqMessage;
import com.yb.guigu.pick.mqbackup.service.IMqMessageService;
import com.yb.guigu.pick.rabbitmq.messager.api.model.MessageContent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;

/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/6/11 21:00
 * FileName: EmailListener
 * Description:
 */

@Component
@Slf4j
public class BackupMQListener {

    @Autowired
    IMqMessageService mqMessageService;


   @RabbitListener(queues = RabbitMQConstant.BackupMQQueueConstant.QUEUE)
    public void handle(@Payload MessageContent<BackupMQSend> result, Message message, Channel channel) throws IOException {
        try {
            String body = new String(message.getBody());
            log.info("body:{}",body);


            BackupMQSend backupMQSend = result.getContent();


            MqMessage mqMessage=new MqMessage();

            BeanUtils.copyProperties(backupMQSend,mqMessage);

            mqMessage.setCreateTime(LocalDateTime.now());

            mqMessageService.save(mqMessage);

            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){

            log.error("MobileListener:{}",e);

            channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
        }
    }


}
